package com.beaven.imserver.net.service;

import com.beaven.imserver.net.bean.api.account.UpdatePwdModel;
import com.beaven.imserver.net.bean.api.base.PushModel;
import com.beaven.imserver.net.bean.api.base.ResponseModel;
import com.beaven.imserver.net.bean.api.user.UpdateInfoModel;
import com.beaven.imserver.net.bean.card.UserCard;
import com.beaven.imserver.net.bean.db.Category;
import com.beaven.imserver.net.bean.db.User;
import com.beaven.imserver.net.bean.db.UserFollow;
import com.beaven.imserver.net.factory.CategoryFactory;
import com.beaven.imserver.net.factory.PushFactory;
import com.beaven.imserver.net.factory.UserFactory;
import com.google.common.base.Strings;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * author: Beaven
 * time: 2017/5/19 14:53
 */
@Path("/user")
public class UserService extends BaseService {

  // 个人信息的修改
  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public ResponseModel<UserCard> update(UpdateInfoModel model) {
    if (!UpdateInfoModel.check(model)) {
      return ResponseModel.buildParameterError();
    }

    User self = getSelf();
    // 更新用户信息
    self = model.updateToUser(self);
    self = UserFactory.updateUser(self);
    // 构架自己的用户信息
    UserCard card = new UserCard(self);
    // 返回
    return ResponseModel.buildOk(card);
  }

  // 修改密码
  @PUT
  @Path("/update")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public ResponseModel<UserCard> updatePwd(UpdatePwdModel model) {
    if (!UpdatePwdModel.check(model)) {
      return ResponseModel.buildParameterError();
    }
    User user = getSelf();
    if (!Objects.equals(user.getPassword(), model.getOldPassword())) {
      return ResponseModel.buildParameterError();
    }
    user = model.updateToUser(user);
    user = UserFactory.updateUser(user);
    UserCard card = new UserCard(user);
    return ResponseModel.buildOk(card);
  }

  // 用户搜索
  @GET
  @Path("/search/{name:(.*)?}")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public ResponseModel<List<UserCard>> searchUser(
      @DefaultValue("") @PathParam("name") String name) {

    List<User> searchUserList = UserFactory.searchUser(name);
    List<User> contactList = UserFactory.contacts(getSelf());

    List<UserCard> userCardList = searchUserList.stream().map(user -> {
      boolean isFollow =
          user.getId().toLowerCase().equals(getSelf().getId()) || contactList.stream()
              .anyMatch(user1 -> user1.getId().equalsIgnoreCase(user.getId()));
      return new UserCard(user, isFollow);
    }).collect(Collectors.toList());
    return ResponseModel.buildOk(userCardList);
  }

  @GET
  @Path("/user/{userId}")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public ResponseModel<UserCard> getUser(@PathParam("userId") String userId) {
    User user = UserFactory.findById(userId);
    UserCard userCard = new UserCard(user);
    return ResponseModel.buildOk(userCard);
  }

  // 获取好友
  @GET
  @Path("/contact")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public ResponseModel<List<UserCard>> contract() {
    User self = getSelf();
    // 拿到我的联系人
    List<User> users = UserFactory.contacts(self);
    // 转换为UserCard
    List<UserCard> userCards = users.stream()
        // map操作，相当于转置操作，User->UserCard
        .map(user -> {
          UserFollow userFollow = UserFactory.getUserFollow(getSelf(), user);
          return new UserCard(user, userFollow.getCategoryId(), true);
        })
        .collect(Collectors.toList());
    // 返回
    return ResponseModel.buildOk(userCards);
  }

  // 添加好友
  @PUT
  @Path("/follow/{userId}/{categoryId}")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public ResponseModel<UserCard> addUser(@PathParam("userId") String userId,
      @PathParam("categoryId") String categoryId) {
    User self = getSelf();
    // 不能添加自己为好友
    if (self.getId().equalsIgnoreCase(userId) || Strings.isNullOrEmpty(userId)) {
      return ResponseModel.buildParameterError();
    }

    User followUser = UserFactory.findById(userId);
    if (followUser == null) {
      // 未找到人
      return ResponseModel.buildAccountError(null);
    }
    Category category = CategoryFactory.queryById(self, categoryId);
    followUser = UserFactory.follow(self, followUser, category, null);
    if (followUser == null) {
      // 关注失败，返回服务器异常
      return ResponseModel.buildServiceError();
    }
    Category category1 = CategoryFactory.queryByName(followUser, UserFactory.CATEGORY_DEFAULT);
    PushFactory.pushUser(PushModel.ENTITY_TYPE_ADD_FRIEND, followUser,
        new UserCard(self, category1.getId(), true));
    // 返回好友的信息
    return ResponseModel.buildOk(new UserCard(followUser, true));
  }

  @PUT
  @Path("/delete/{userId}")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public ResponseModel<UserCard> deleteUser(@PathParam("userId") String userId) {
    User self = getSelf();
    // 不能删除自己
    if (self.getId().equalsIgnoreCase(userId) || Strings.isNullOrEmpty(userId)) {
      return ResponseModel.buildParameterError();
    }
    User deleteUser = UserFactory.findById(userId);

    PushFactory.pushUser(PushModel.ENTITY_TYPE_DELETE_FRIEND, deleteUser, new UserCard(self));
    UserFactory.delete(self, deleteUser);
    return ResponseModel.buildOk(new UserCard(deleteUser));
  }
}
